import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
import axios from 'axios';
import { AntDesign, Feather } from '@expo/vector-icons';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';

// 定义导航参数类型
type RootStackParamList = {
  Individual: undefined;
  Edit: { userData: UserData };
};

type NavigationProp = StackNavigationProp<RootStackParamList, 'Individual'>;

// 定义用户数据接口
interface UserData {
  _id?: string;
  name: string;
  old: string;
  img: string;
  profile: string;
  grade: string;
  address: string;
}

// 定义MenuItem组件的Props接口
interface MenuItemProps {
  icon: 'book' | 'clockcircle' | 'star' | 'setting';  // 限定具体的图标名称
  title: string;
}

const Individual: React.FC = () => {
  const navigation = useNavigation<NavigationProp>();
  const [userData, setUserData] = useState<UserData>({
    name: '',
    old: '',
    img: '',
    profile: '',
    grade: '',
    address: ''
  });

  const fetchUserData = async (): Promise<void> => {
    try {
      const response = await axios.get('http://172.20.10.3:3000/cyw/pi');
      if (response.data.code === 200 && response.data.pilist.length > 0) {
        const user = response.data.pilist[0];
        setUserData({
          _id: user._id,
          name: user.name,
          old: user.old,
          img: user.img,
          profile: user.profile,
          grade: user.grade,
          address: user.address
        });
      }
    } catch (error) {
      console.error('Error fetching user data:', error);
    }
  };

  useEffect(() => {
    fetchUserData();
  }, []);

  useFocusEffect(
    useCallback(() => {
      fetchUserData();
    }, [])
  );

  return (
    <ScrollView style={styles.container}>
      <View style={styles.headerBar}>
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <AntDesign name="left" size={24} color="#333" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>个人资料</Text>
      </View>
      <View style={styles.bj}>
        <Image
          style={styles.avatar1}
          source={require('../../../assets/背景1.jpg')}
        />
      </View>
      <View style={styles.headerA}>
        {/* 顶部用户信息区域 */}
        <View style={styles.header}>
          <View style={styles.avatarContainer}>
            <Image
              style={styles.avatar}
              source={require('../../../assets/hellokitty.jpg')}
            />
            <TouchableOpacity
              style={styles.editButton}
              onPress={() => navigation.navigate('Edit', { userData })}
            >
              <Feather name="edit-2" size={16} color="#666" />
              <Text style={styles.editText}>编辑资料</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.userInfo}>
            <View style={styles.nameRow}>
              <Text style={styles.name}>{userData.name}</Text>
              <View style={styles.levelBadge}>
                <Text style={styles.levelText}>激活等级</Text>
              </View>
            </View>

            <View style={styles.schoolRow}>
              <Text style={styles.school}>{userData.address || '暂未填写学校'}</Text>
              <Text style={styles.grade}>{userData.grade} ▼</Text>
            </View>

            <View style={styles.socialRow}>
              <Text style={styles.socialText}>0 粉丝</Text>
              <Text style={styles.socialText}>0 关注</Text>
            </View>

            <TouchableOpacity style={styles.bioContainer}>
              <Text style={styles.bioText}>
                {userData.profile || '你还没有个人简介，点击添加'}
              </Text>
            </TouchableOpacity>

            <View style={styles.ipContainer}>
              <Text style={styles.ipText}>IP 属地: 河北省</Text>
              <Text style={styles.emoji}>😊</Text>
            </View>
          </View>
        </View>

        {/* 目标学校区域 */}
        <TouchableOpacity style={styles.targetSchoolContainer}>
          <Text style={styles.targetSchoolText}>目标学校：快来设置目标学校吧~</Text>
          <AntDesign name="right" size={16} color="#999" />
        </TouchableOpacity>

        {/* 我的成就区域 */}
        <TouchableOpacity style={styles.achievementContainer}>
          <View style={styles.achievementHeader}>
            <Text style={styles.achievementTitle}>我的成就</Text>
          </View>
          <View style={styles.achievementProgress}>
            <Text style={styles.achievementCount}>帮帮新人</Text>
            <Text style={styles.achievementCount}>个人招牌</Text>
          </View>
          <View style={styles.badgeContainer}>
            {/* 其他徽章内容 */}
          </View>
        </TouchableOpacity>

        {/* 其他功能区 */}
        <View style={styles.menuContainer}>
          <MenuItem icon="book" title="我的收藏" />
          <MenuItem icon="clockcircle" title="学习记录" />
          <MenuItem icon="star" title="我的积分" />
          <MenuItem icon="setting" title="设置" />
        </View>
      </View>
    </ScrollView>
  );
};

// 菜单项组件
const MenuItem: React.FC<MenuItemProps> = ({ icon, title }) => {
  return (
    <TouchableOpacity style={styles.menuItem}>
      <View style={styles.menuIcon}>
        <AntDesign name={icon} size={20} color="#333" />
      </View>
      <Text style={styles.menuText}>{title}</Text>
      <AntDesign name="right" size={16} color="#999" />
    </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#C0C0C0',
  },
  headerBar: {
    width: '100%',
    height: 55,
    flexDirection: 'row',
    alignItems: 'center',
    padding: 10,
    backgroundColor: '#fff',
    marginBottom: 15,
    position: 'relative',
  },
  backButton: {
    padding: 5,
    position: 'absolute',
    left: 10,
    zIndex: 1,
  },
  headerTitle: {
    flex: 1,
    fontSize: 20,
    fontWeight: 'bold',
    color: '#222',
    textAlign: 'center',
  },
  bj: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
  },
  avatar1: {
    width: '100%',
    height: 230,
  },
  headerA: {
    backgroundColor: '#FFFFFF',
    marginTop: 160,
  },
  header: {
    flexDirection: 'row',
    padding: 20,
    backgroundColor: '#fff',
    marginBottom: 15,
    borderBottomColor: '#E0E0E0'
  },
  avatarContainer: {
    position: 'relative',
    marginRight: 20,
    marginTop: -60,
  },
  avatar: {
    width: 90,
    height: 90,
    borderRadius: 45,
  },
  editButton: {
    flexDirection: 'row',
    alignItems: 'center',
    position: 'absolute',
    bottom: 180,
    right: -450,
    backgroundColor: '#fff',
    borderRadius: 15,
    padding: 6,
    elevation: 2,
  },
  editText: {
    marginLeft: 5,
    fontSize: 14,
    color: '#666',
  },
  userInfo: {
    flex: 1,
    marginTop: 50,
    marginLeft: -90,
  },
  nameRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  name: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#222',
  },
  levelBadge: {
    backgroundColor: '#FFF0E6',
    borderRadius: 6,
    paddingHorizontal: 8,
    paddingVertical: 4,
    marginLeft: 12,
  },
  levelText: {
    fontSize: 14,
    color: '#FF6B00',
  },
  schoolRow: {
    flexDirection: 'row',
    marginBottom: 8,
  },
  school: {
    fontSize: 18,
    color: '#666',
  },
  grade: {
    fontSize: 18,
    color: '#666',
  },
  socialRow: {
    flexDirection: 'row',
    marginBottom: 12,
  },
  socialText: {
    fontSize: 16,
    color: '#666',
  },
  bioContainer: {
    marginBottom: 12,
  },
  bioText: {
    fontSize: 16,
    color: '#999',
  },
  ipContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  ipText: {
    fontSize: 16,
    color: '#999',
  },
  emoji: {
    marginLeft: 6,
  },
  targetSchoolContainer: {
    width: 550,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: 18,
    backgroundColor: '#F5F8FA',
    marginBottom: 15,
    marginLeft: 25,
    borderRadius: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0'
  },
  targetSchoolText: {
    fontSize: 16,
    color: '#333',
  },
  achievementContainer: {
    height: 200,
    padding: 18,
    backgroundColor: '#fff',
    marginBottom: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#E0E0E0'
  },
  achievementHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 18,
  },
  achievementTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#222',
  },
  achievementProgress: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  achievementCount: {
    fontSize: 18,
    color: '#666',
    marginRight: 8,
  },
  badgeContainer: {
    flexDirection: 'row',
  },
  menuContainer: {
    backgroundColor: '#fff',
  },
  menuItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 18,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: '#f0f0f0',
  },
  menuIcon: {
    marginRight: 18,
  },
  menuText: {
    flex: 1,
    fontSize: 18,
    color: '#333',
  },
});

export default Individual;